# File: run.py (Runs the MCP Server via Uvicorn/SSE)

import uvicorn
import os
import sys
from pathlib import Path
from dotenv import load_dotenv

# --- Path Setup ---
project_root = Path(__file__).parent
src_path = project_root / "src"
if str(src_path) not in sys.path:
    sys.path.insert(0, str(src_path))
    print(f"[run.py] Added src path to sys.path: {src_path}")

# --- Environment Setup ---
env_path = project_root / ".env"
if env_path.exists():
    load_dotenv(dotenv_path=env_path)
    print(f"[run.py] Loaded environment variables from {env_path}")
else:
    print(f"[run.py] .env file not found at {env_path}, skipping.")

# --- App Import ---
# *** Corrected path to the 'app' variable defined in src/mcp_server/app.py ***
uvicorn_app_str = "src.mcp_server.app:app"
print(f"[run.py] Uvicorn target application: {uvicorn_app_str}")

# --- Uvicorn Configuration ---
host = os.getenv("MCP_SERVER_HOST", "127.0.0.1")
port = int(os.getenv("MCP_SERVER_PORT", "8000"))
workers = int(os.getenv("UVICORN_WORKERS", "1")) # Workers > 1 WILL BREAK stateful lifespan (Playwright)
reload = os.getenv("UVICORN_RELOAD", "false").lower() == "true" # reload=True likely breaks lifespan
log_level = os.getenv("UVICORN_LOG_LEVEL", "info") # Changed default to info for less noise

if workers > 1:
     print("[run.py] WARNING: workers > 1 detected. Playwright managed by lifespan requires workers=1. Forcing workers to 1.")
     workers = 1
if reload:
     print("[run.py] WARNING: reload=True enabled. Lifespan functions (like Playwright start/stop) might run multiple times or behave unexpectedly. Consider setting reload=False for stable operation.")

# --- Main Execution ---
if __name__ == "__main__":
    print(f"[run.py] Starting Uvicorn server:")
    print(f"  - Application: {uvicorn_app_str}")
    print(f"  - Host: {host}")
    print(f"  - Port: {port}")
    print(f"  - Workers: {workers}")
    print(f"  - Reload: {reload}")
    print(f"  - Log Level: {log_level}")
    print("Note: Application lifespan (Playwright start/stop) is handled by the ASGI app.")

    try:
        uvicorn.run(
            uvicorn_app_str,
            host=host,
            port=port,
            workers=workers, # MUST be 1 for Playwright lifespan
            log_level=log_level,
            reload=reload,   # Should be False for stable lifespan
            lifespan="on",   # Crucial for triggering app_lifespan
        )
    except ImportError as e:
        print(f"\n[run.py] ERROR: Uvicorn failed to import the application '{uvicorn_app_str}'.", file=sys.stderr)
        print(f"ImportError: {e}", file=sys.stderr)
        print("Check if:", file=sys.stderr)
        print(f"  1. The src directory '{src_path}' is correct and in sys.path.", file=sys.stderr)
        # Corrected path check below
        print("  2. The file 'src/mcp_server/app.py' exists.", file=sys.stderr)
        print("  3. The variable 'app' (result of mcp.sse_app()) is defined at the end of that file.", file=sys.stderr)
        print("  4. There are no import errors within the application modules (check server logs).", file=sys.stderr)
        import traceback
        traceback.print_exc()
        sys.exit(1)
    except TypeError as e:
        print(f"\n[run.py] ERROR: TypeError occurred, possibly the ASGI app '{uvicorn_app_str}' is not valid.", file=sys.stderr)
        print(f"TypeError: {e}", file=sys.stderr)
        # Corrected path check below
        print("Check if 'src/mcp_server/app.py' successfully created the 'app' variable.", file=sys.stderr)
        import traceback
        traceback.print_exc()
        sys.exit(1)
    except Exception as e:
        print(f"\n[run.py] ERROR: An unexpected error occurred while trying to run Uvicorn: {e}", file=sys.stderr)
        import traceback
        traceback.print_exc()
        sys.exit(1)

    print("[run.py] Uvicorn server has stopped.")